<template>
	<el-button :icon="address ? Wallet : ''" :type="address ? 'primary' : 'warning'" @click="ConnectWallet">{{ address ? address.substring(0, 4) + '...' + address.slice(-6) : $t('message.ConnectWallet') }}</el-button>
</template>
<script>
	import { Wallet } from '@element-plus/icons-vue'
	import store from './../store'
	import { mapState } from 'vuex'
	import { checkNetwork, dataRequest as api } from '@/api/api'
	import { ethers } from 'ethers'
	export default {
		props: ['defaultchanid'],
		computed: {
			Wallet() {
				return Wallet // 假设 Edit 是通过 import 引入的 Element Plus 的图标组件
			},
			...mapState(['address', 'chain', 'balance']),
		},
		data() {
			return {}
		},
		name: 'wallet',
		methods: {
			async ConnectWallet() {
				try {
					// 链变化

					if (window.ethereum) {
						this.wallet()
						//链接中断
						const now = new Date()
						window.ethereum.removeAllListeners()
						window.ethereum.on('disconnect', this.wallet)
						window.ethereum.on('chainChanged', async (chainId) => {
							store.commit('setChain', parseInt(chainId, 16))
							this.wallet()
						})
						window.ethereum.on('accountsChanged', this.wallet)
					}
				} catch (error) {
					console.error(error.message)
					this.$message.error(error.message)
					store.commit('setAddress', null)
					store.commit('setBalance', null)
					store.commit('setChain', null)
				}
			},
			async wallet() {
				try {
					let arr = await checkNetwork()
					// 查询余额
					// 使用 Promise.race 包裹获取余额的异步操作和超时
					let balancePromise = ethereum.request({
						method: 'eth_getBalance',
						params: [arr[0], 'latest'],
						id: 1,
					})

					let Balance = await Promise.race([balancePromise.then(ethers.formatEther), this.timeout(5000)])
					store.commit('setBalance', Balance)

					// 使用 Promise.race 包裹获取链ID的异步操作和超时

					// let chainId = parseInt(window.ethereum.chainId, 16)
					let chainId = parseInt(await ethereum.request({ method: 'eth_chainId' }))

					// 在这里提示用户切换链
					// 并提示当前支持的链
					store.commit('setChain', chainId)
					store.commit('setAddress', arr[0])
					if (this.defaultchanid && this.defaultchanid != '0' && chainId != this.defaultchanid) {
						console.log(this.defaultchanid)
						let arr = await api('Query', 'chain', this.defaultchanid)
						// 这里提示切换一个链
						if (arr.code == 200) {
							this.$confirm(this.$t('message.Switch') + arr.data.name + '?', this.$t('el.messagebox.title'), {
								confirmButtonText: this.$t('el.colorpicker.confirm'),
								cancelButtonText: this.$t('el.datepicker.cancel'),
								type: 'warning',
							})
								.then(() => {
									this.switchEth(arr)
								})
								.catch(() => {})
						}
					}
					// 这里应该有超时才对
				} catch (error) {
					this.$message.error(error.message)
					store.commit('setAddress', null)
					store.commit('setBalance', null)
					store.commit('setChain', null)
				}
			},
			async switchEth(arr) {
				try {
					await ethereum.request({
						method: 'wallet_addEthereumChain',
						params: [
							{
								chainId: ethers.toBeHex(this.defaultchanid), // 56 in decimal (Binance Smart Chain)
								chainName: arr.data.name,
								nativeCurrency: {
									symbol: arr.data.symbol,
									decimals: 18,
								},
								rpcUrls: [arr.data.rpc],
								blockExplorerUrls: [arr.data.blockExplorerUrls],
							},
						],
					})
				} catch (error) {
					console.log(error)
				}
			},
			// 超时
			timeout(ms) {
				return new Promise((_, reject) => {
					// 在指定时间后reject Promise，表示超时
					setTimeout(() => {
						reject(new Error('Timeout exceeded'))
					}, ms)
				})
			},
			// 添加一个链到钱包
			async addCustomChainToWallet() {
				try {
					await window.ethereum.request({
						method: 'wallet_addEthereumChain',
						params: [
							{
								chainId: '0x1', // 你要添加的链的ID
								chainName: 'Custom Network', // 链的名称
								nativeCurrency: {
									name: 'Custom Token', // 本地代币的名称
									symbol: 'CT', // 本地代币的符号
									decimals: 18, // 本地代币的小数位数
								},
								rpcUrls: ['https://custom-network-rpc-url.com'], // RPC 端点列表
								blockExplorerUrls: ['https://custom-network-explorer-url.com'], // 区块浏览器 URL
							},
						],
					})
				} catch (error) {
					console.error('Failed to add Custom Network to wallet:', error)
				}
			},
		},
		mounted() {
			this.ConnectWallet()
		},
		beforeRouteLeave() {
			if (window.ethereum) {
				window.ethereum.removeListener('disconnect', this.wallet)
				window.ethereum.removeListener('chainChanged', this.wallet)
				window.ethereum.removeListener('accountsChanged', this.wallet)
			}
		},
	}
</script>
